<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------
namespace Admin\Service;
use Admin\Controller\OssController;
use Admin\Enums\AuthorType;

/**
 * 谱单服务
 * @author Administrator
 *
 */
class ScoreService{
	
    /**
     * 新增谱单
     */
    public function add(){
        $param = I('post.');
        
        //step-1: 验证参数
        $Model = D('Score');
        $data = $Model->create($param);
        if($data){
            //step-2: 设置默认参数
            $param = $this->fillParam($param);
            //step-3: 保存谱单
            $id = $Model->add($param);

            //step-4:将本地图片上传阿里云
            $ossController = new OssController();
            $imageIds = $ossController->uploadScore($param);

            
            //step-4: 保存曲谱和图片的关系
            $imageScoreService = new ImageScoreService();
            $imageScoreService->save($imageIds, $id);
            
            //step-5: 保存标签
            $tags = explode("," ,$param['tags']);
            $tagService = new TagService();
            foreach ($tags as $key=>$name) {
                $tag['name'] = $name;
                $tag_id = $tagService->save($tag);
                $tag['id']  = $tag_id;
                $tags[$key] = $tag;
            }
            
            //step-6: 保存标签和曲谱的关系
            $tag_ids = array_column($tags, "id");
            $tagSheetService = new TagSheetService();
            $tagSheetService->save($tag_ids, $id);
            
            return $id;
        } else {
            E($Model->getError());
        }
        
	}
	
	/**
	 * 编辑谱单
	 */
	public function edit(){
	    $param = I('post.');
	    //step-1: 验证参数
	    $Model = M('Score');
	    $data = $Model->create($param);
	    if($data){
	        //step-2: 设置默认参数
	        $param['updator']  = UID;
	        $param['update_time']  = date('Y-m-d H:i:s', time());
	
	        //step-3: 保存谱单
	        $id = $Model->save($param);

            //step-4:将本地图片上传阿里云
            $ossController = new OssController();
            $imageIds = $ossController->uploadScore($param);
	
	        //step-5: 保存曲谱和图片的关系
	        $imgScoreService = new ImageScoreService();
	        $imgScoreService->save($imageIds, $param['id']);
	
	        //step-6: 保存标签
	        $tags = explode("," ,$param['tags']);
            $tagService = new TagService();
            foreach ($tags as $key=>$name) {
                $tag['name'] = $name;
                $tag_id = $tagService->save($tag);
                
                $tag['id']  = $tag_id;
                $tags[$key] = $tag;
                
                unset($tag);
            }
            
            //step-7: 保存标签和曲谱的关系
            $tag_ids = array_column($tags, "id");
            
            $tagScoreService = new TagScoreService();
            $tagScoreService->save($tag_ids, $param['id']);
	
	        return $id;
	    } else {
	        E($Model->getError());
	    }
	
	}
	
	/**
	 * 填充参数
	 * @param unknown $param
	 */
	private function fillParam($param){
	    $param['author_type'] = AuthorType::$ADMIN;
	    $param['creator'] = 2; //xiesi
	    //$param['checker'] = UID;
	    //$param['check_time'] = date('Y-m-d H:i:s',time());
	    return $param;
	}

    /**
     * 获取谱单内曲谱数、评论数、分享数、收藏数、点击数
     */
    public function getScoreCount($list)
    {
        $scoreIds = array_column($list, 'id') ? array_column($list, 'id') : array_column($list, 'score_id');
        //1.获取曲谱数
        $sheetCountService = new ScoreSheetService();
        $sheetCountMap = $sheetCountService->getSheetCount($scoreIds);
        //2.获取评论数
        $commentService = new ScoreCommentService();
        $scoreCommentCount = $commentService->multiCommentCount($scoreIds);

        //3.获取分享数 TODO::
        //4.获取收藏数
        $favService = new ScoreFavoriteService();
        $scoreFavCount = $favService->multiFavCount($scoreIds);
        if ($list[0]['id']) {
            foreach ($list as $key => $score) {
                $list[$key]['sheet_count'] = $sheetCountMap[$score['id']] ? $sheetCountMap[$score['id']] : 0;
                $list[$key]['comment_count'] = $scoreCommentCount[$score['id']] ? $scoreCommentCount[$score['id']] : 0;
                $list[$key]['fav_count'] = $scoreFavCount[$score['id']] ? $scoreFavCount[$score['id']] : 0;
            }
        } elseif ($list[0]['score_id']) {
            foreach ($list as $key => $score) {
                $list[$key]['sheet_count'] = $sheetCountMap[$score['score_id']] ? $sheetCountMap[$score['score_id']] : 0;
                $list[$key]['comment_count'] = $scoreCommentCount[$score['score_id']] ? $scoreCommentCount[$score['score_id']] : 0;
                $list[$key]['fav_count'] = $scoreFavCount[$score['score_id']] ? $scoreFavCount[$score['score_id']] : 0;
            }
        }
        return $list;
    }

    /**
     * 补充谱单创建者信息及标签信息
     * @param $list
     * @return array
     */
	public function convertList($list, $order = 'id', $sort = 1){
        //step-1: 根据创建者类型分为两组
        foreach ($list as $key => $val) {
            if ($val['author_type'] == AuthorType::$ADMIN) {
                $admin[] = $val;
            } else {
                $user[] = $val;
            }
        }

        if (!empty($user)) {
            $creatorIdList = array_column($user,'creator');
            $userService = new UserService();
            $creatorMap = $userService->getUserInfoByIds($creatorIdList);

            //step-2: 自动填充标签
            $scoreIdList = array_column($user,'id');
            $tagScoreService = new TagScoreService();
            $tagsMap = $tagScoreService->getTagsByScoreIds($scoreIdList);

            foreach ($user as $key=>$val) {
                $creator = $creatorMap[$val['creator']];
                $user[$key]['creator'] = $creator;
                $user[$key]['tags'] = $tagsMap[$val['id']];
            }
        }
        if (!empty($admin)) {
            $creatorIdList = array_column($admin,'creator');
            $memberService = new MemberService();
            $creatorMap = $memberService->getMapByUids($creatorIdList);

            //step-2: 自动填充标签
            $scoreIdList = array_column($admin,'id');
            $tagScoreService = new TagScoreService();
            $tagsMap = $tagScoreService->getTagsByScoreIds($scoreIdList);

            foreach ($admin as $key=>$val) {
                $creator = $creatorMap[$val['creator']];
                $admin[$key]['creator'] = $creator;
                $admin[$key]['tags'] = $tagsMap[$val['id']];
            }
        }

        if (empty($user)) {
            $list = $admin;
        } elseif (empty($admin)) {
            $list = $user;
        } else {
            $list = array_merge($admin, $user);
        }

        //对数组进行重新排序
        if ($sort == 2) {
            $list = my_sort($list, $order, SORT_DESC);
        } else {
            $list = my_sort($list, $order);
        }


        return $list;
	}

    /**
     * 设置专区谱单置顶
     * @return mixed
     */
    public function setZoneTop($model, $id, $isTop)
    {
        $data = array('is_top'=>$isTop);
        $res = M($model)->where(array('score_id'=>$id))->save($data);
        return $res;
    }

    /**
     * 专区添加谱单
     */
    public function addScoreToZone($scoreIds, $model)
    {
        $list = array();
        foreach ($scoreIds as $key=>$scoreId){
            $list[] = array(
                'score_id' => $scoreId,
                'creator'  => UID,
                'create_time' => date('Y-m-d H:i:s', time())
            );
        }

        $Model = M($model);
        return $Model->addAll($list);
    }

    /**
     * 获取谱单的基本信息
     * @param $scoreIds
     * @return array
     */
    public function getScoreInfoByIds($scoreIds)
    {
        $map = array('id' => array('in', $scoreIds));

        $Model = M('Score');
        $scoreList = $Model->where($map)->select();
        $scoreMap = array();
        foreach ($scoreList as $key=> $val) {
            $scoreMap[$val['id']] = $val;
        }
        return $scoreMap;
    }
	
}